<?php
use think\migration\Migrator;
use think\migration\db\table;

class SeedVariedComputerQuestions extends Migrator
{
    public function up()
    {
        $time = time();
        $types = ['single','multi','judge','blank','short'];

        // delete previously seeded questions of these types
        $this->execute("DELETE FROM `ba_exam_question` WHERE `type` IN ('".implode("','", $types)."')");

        $rows = [];

        // helper to make option map
        $makeOptions = function(array $texts){
            $obj = [];
            foreach($texts as $i=>$t){
                $k = chr(65 + $i);
                $obj[$k] = $t;
            }
            return $obj;
        };

        // We'll generate 50 varied items per type by cycling through template pools
        $singleTemplates = [
            [
                'q' => '单选：下列哪个端口通常用于 HTTPS？ (#%d)',
                'opts' => ['80','22','443','21'],
                'ans' => 'C'
            ],
            [
                'q' => '单选：哪种存储类型属于关系型数据库？ (#%d)',
                'opts' => ['MongoDB','MySQL','Redis','Elasticsearch'],
                'ans' => 'B'
            ],
            [
                'q' => '单选：下列哪项不是操作系统的功能？ (#%d)',
                'opts' => ['进程管理','内存管理','设备管理','编译源码'],
                'ans' => 'D'
            ],
            [
                'q' => '单选：HTTP 的无状态特性意味着？ (#%d)',
                'opts' => ['服务器不保存客户端状态','只能用 GET 方法','必须使用 TLS','需要登录才能使用'],
                'ans' => 'A'
            ],
        ];

        $multiTemplates = [
            [
                'q' => '多选：下面哪些协议工作在传输层或以上？ (#%d)',
                'opts' => ['HTTP','TCP','UDP','FTP'],
                'ans' => ['B','C']
            ],
            [
                'q' => '多选：以下哪些属于常见的 JavaScript 数据类型？ (#%d)',
                'opts' => ['String','Number','Boolean','Class'],
                'ans' => ['A','B','C']
            ],
            [
                'q' => '多选：哪些属于常见的数据库索引类型？ (#%d)',
                'opts' => ['B-Tree','Hash','Full-Text','LRU'],
                'ans' => ['A','B','C']
            ],
        ];

        $judgeTemplates = [
            [ 'q' => '判断：TCP 是一种面向连接的协议。 (#%d)', 'ans' => 'A' ],
            [ 'q' => '判断：HTML 是一种编程语言。 (#%d)', 'ans' => 'B' ],
            [ 'q' => '判断：SSD 比 HDD 速度慢。 (#%d)', 'ans' => 'B' ],
        ];

        $blankTemplates = [
            [ 'q' => '填空：HTTP 的默认端口是 ____ 。 (#%d)', 'ans' => '80' ],
            [ 'q' => '填空：常用的安全加密协议是 ____ 。 (#%d)', 'ans' => 'TLS' ],
            [ 'q' => '填空：表示文件只读的 Unix 权限位是 ____ 。 (#%d)', 'ans' => 'r--' ],
        ];

        $shortTemplates = [
            [ 'q' => '简答：简述进程与线程的区别。 (#%d)', 'ans' => '进程是资源分配的单位，线程是调度的单位，线程在进程内共享资源。' ],
            [ 'q' => '简答：简要说明 RESTful 风格的特点。 (#%d)', 'ans' => '基于资源、使用 HTTP 动词、无状态、统一接口。' ],
            [ 'q' => '简答：什么是事务的 ACID 特性？简要说明每项含义。 (#%d)', 'ans' => 'ACID：原子性、一致性、隔离性、持久性。' ],
        ];

        // generate single
        for($i=1;$i<=50;$i++){
            $tpl = $singleTemplates[($i-1) % count($singleTemplates)];
            $content = sprintf($tpl['q'], $i);
            $opts = $makeOptions($tpl['opts']);
            $rows[] = [
                'type'=>'single',
                'content'=>$content,
                'options'=>json_encode($opts, JSON_UNESCAPED_UNICODE),
                'answer'=>$tpl['ans'],
                'score'=>5,
                'analysis'=>'参考网络与数据库基础知识。',
                'create_time'=>$time + $i,
                'update_time'=>$time + $i
            ];
        }

        // generate multi
        for($i=1;$i<=50;$i++){
            $tpl = $multiTemplates[($i-1) % count($multiTemplates)];
            $content = sprintf($tpl['q'], $i);
            $opts = $makeOptions($tpl['opts']);
            $ans = implode(',', $tpl['ans']);
            $rows[] = [
                'type'=>'multi',
                'content'=>$content,
                'options'=>json_encode($opts, JSON_UNESCAPED_UNICODE),
                'answer'=>$ans,
                'score'=>5,
                'analysis'=>'根据协议/语言/索引等基础知识判断。',
                'create_time'=>$time + 100 + $i,
                'update_time'=>$time + 100 + $i
            ];
        }

        // generate judge
        for($i=1;$i<=50;$i++){
            $tpl = $judgeTemplates[($i-1) % count($judgeTemplates)];
            $content = sprintf($tpl['q'], $i);
            $opts = $makeOptions(['对','错']);
            $rows[] = [
                'type'=>'judge',
                'content'=>$content,
                'options'=>json_encode($opts, JSON_UNESCAPED_UNICODE),
                'answer'=>$tpl['ans'],
                'score'=>2,
                'analysis'=>'判断题基于常识或技术定义。',
                'create_time'=>$time + 200 + $i,
                'update_time'=>$time + 200 + $i
            ];
        }

        // generate blank
        for($i=1;$i<=50;$i++){
            $tpl = $blankTemplates[($i-1) % count($blankTemplates)];
            $content = sprintf($tpl['q'], $i);
            $rows[] = [
                'type'=>'blank',
                'content'=>$content,
                'options'=>null,
                'answer'=>$tpl['ans'],
                'score'=>3,
                'analysis'=>'简答或填空题以关键字/值为评分点。',
                'create_time'=>$time + 300 + $i,
                'update_time'=>$time + 300 + $i
            ];
        }

        // generate short
        for($i=1;$i<=50;$i++){
            $tpl = $shortTemplates[($i-1) % count($shortTemplates)];
            $content = sprintf($tpl['q'], $i);
            $rows[] = [
                'type'=>'short',
                'content'=>$content,
                'options'=>null,
                'answer'=>$tpl['ans'],
                'score'=>10,
                'analysis'=>'参考答案提供要点即可评分。',
                'create_time'=>$time + 400 + $i,
                'update_time'=>$time + 400 + $i
            ];
        }

        // Insert rows in batches
        $chunks = array_chunk($rows, 100);
        foreach($chunks as $chunk){
            $values = [];
            foreach($chunk as $r){
                $vals = [];
                foreach(['type','content','options','answer','score','analysis','create_time','update_time'] as $c){
                    if (!array_key_exists($c, $r) || $r[$c] === null) $vals[] = 'NULL';
                    else $vals[] = "'".addslashes($r[$c])."'";
                }
                $values[] = "(".implode(",", $vals).")";
            }
            $sql = "INSERT INTO `ba_exam_question` (`type`,`content`,`options`,`answer`,`score`,`analysis`,`create_time`,`update_time`) VALUES ".implode(',', $values);
            $this->execute($sql);
        }
    }

    public function down()
    {
        $types = ['single','multi','judge','blank','short'];
        $this->execute("DELETE FROM `ba_exam_question` WHERE `type` IN ('".implode("','", $types)."')");
    }
}
